package com.yksj.healthtalk.ui.interestwall;

import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.db.ChatUserHelper;
import com.yksj.healthtalk.entity.BaseInfoEntity;
import com.yksj.healthtalk.entity.MessageEntity;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * 转发界面
 * 
 * @author crj
 * 
 */
public class TransmitActivity extends BaseFragmentActivity implements
		OnClickListener {
	
	private int type;// 放入smartfox内的标志位 话题2,好友1
	private String cusIds;// 一连串以逗号分隔的id
	private String picId;
	private TransmitFragment fragment;
	
	Button confirmButton;
	private int sendState = 0;// 0转发成功,1表示转发失败

	final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// 保存消息到数据库
			if (msg.what == 1) {
				final MessageEntity[] entities = (MessageEntity[]) msg.obj;
				new Thread() {
					public void run() {
						ChatUserHelper helper = ChatUserHelper.getInstance();
						List<BaseInfoEntity> list = fragment.getSelectedList();
						if (entities[0] != null) {
							MessageEntity entity = entities[0];
							for (BaseInfoEntity baseInfoEntity : list) {
								entity.setReceiverId(baseInfoEntity.getId());
								helper.insertChatMessage(entity);
							}
						}
						if (entities[1] != null) {
							MessageEntity entity = entities[1];
							for (BaseInfoEntity baseInfoEntity : list) {
								entity.setReceiverId(baseInfoEntity.getId());
								helper.insertChatMessage(entity);
							}
						}
					};
				}.start();
			}
		}
	};

	final BroadcastReceiver mReceiver = new BroadcastReceiver() {
		public void onReceive(android.content.Context context, Intent intent) {
			if ("y".equalsIgnoreCase(intent.getStringExtra("FLAG"))) {
				sendState = 1;
				ToastUtil.showShort(getApplicationContext(), "转发成功");
				// 好友转发消息需要保存到本地
				if (type == 1) {
					Message message = mHandler.obtainMessage();
					message.obj = new MessageEntity[] {
							(MessageEntity) intent.getSerializableExtra("picture"),
							(MessageEntity) intent.getSerializableExtra("text") };
					message.what = 1;
					mHandler.sendMessage(message);
				}
				onBackPressed();
			} else {
				ToastUtil.showShort(getApplicationContext(), "转发失败");
				sendState = 0;
			}
		};
	};

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.transmit_activity_main);
		Intent intent = getIntent();
		type = intent.getIntExtra("type", 1);
		picId = intent.getStringExtra("picId");

		initView();
	}

	public void initView() {
		initTitle();
		titleLeftBtn.setOnClickListener(this);
		if (type != 1) {
			titleTextV.setText("转发给好友");
		} else {
			titleTextV.setText("转发到话题");
		}
		titleRightBtn2.setVisibility(View.VISIBLE);
		titleRightBtn2.setText("确定");
		titleRightBtn2.setOnClickListener(this);
		FragmentManager manager = this.getSupportFragmentManager();
		FragmentTransaction mFragmentTransaction = manager.beginTransaction();
		
		// mFragmentTransaction.setCustomAnimations(R.anim.slide_in_left,
		// R.anim.slide_out_right);
		
		fragment = TransmitFragment.newInstance(String.valueOf(type));
		mFragmentTransaction.add(R.id.fragmentContent, fragment);
		mFragmentTransaction.commit();
	}

	@Override
	protected void onStop() {
		super.onStop();
		unregisterReceiver(mReceiver);
	}

	@Override
	protected void onStart() {
		super.onStart();
		IntentFilter filter = new IntentFilter(MessagePushService.ACTION_REPEAT_STATE);
		registerReceiver(mReceiver, filter);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.title_right2:
			cusIds = fragment.getCusIds();
			if (!TextUtils.isEmpty(cusIds)) {
				SmartFoxClient.sendRepeatToFriend(String.valueOf(type), cusIds,picId);
			} else {
				ToastUtil.showShort(getApplicationContext(), "转发失败");
			}
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Intent intent = getIntent();
			intent.putExtra("sendState", sendState);
			setResult(RESULT_OK, intent);
			this.finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onBackPressed() {
		Intent intent = getIntent();
		intent.putExtra("sendState", sendState);
		setResult(RESULT_OK, intent);
		this.finish();
	}
}
